package com.gyc.game.cchess.model;

import java.util.Arrays;

public class HistoryHeuristic {

	int m_HistoryTable[];// 90*90

	ChessMove m_TargetBuff[];// 100

	public HistoryHeuristic() {
		super();

		m_HistoryTable = new int[8100];// 90*90
		m_TargetBuff = new ChessMove[100];// 100
		for (int i = 0; i < m_TargetBuff.length; i++) {
			m_TargetBuff[i] = new ChessMove();
		}
	}

	public void ResetHistoryTable() {
		Arrays.fill(m_HistoryTable, 10);
	}

	public int GetHistoryScore(ChessMove move) {
		return m_HistoryTable[move.fRowColumn * 90 + move.tRowColumn];
	}

	public void EnterHistoryScore(ChessMove move, int depth) {
		int nFrom, nTo;
		nFrom = move.fRowColumn;
		nTo = move.tRowColumn;
		m_HistoryTable[nFrom * 90 + nTo] += 2 << depth;
	}

	//
	public void Merge_Asc(ChessMove[] source, ChessMove[] target, int l, int m,
			int r) {// 从小到大排序
		int i = l;
		int j = m + 1;
		int k = l;

		while ((i <= m) && (j <= r))
			if (source[i].Score <= source[j].Score)
				target[k++] = source[i++];
			else
				target[k++] = source[j++];

		if (i > m)
			for (int q = j; q <= r; q++)
				target[k++] = source[q];
		else
			for (int q = i; q <= m; q++)
				target[k++] = source[q];
	}

	public void Merge_Desc(ChessMove[] source, ChessMove[] target, int l,
			int m, int r) {// 从大到小排序
		int i = l;
		int j = m + 1;
		int k = l;

		while ((i <= m) && (j <= r))
			if (source[i].Score >= source[j].Score)
				target[k++] = source[i++];
			else
				target[k++] = source[j++];

		if (i > m)
			for (int q = j; q <= r; q++)
				target[k++] = source[q];
		else
			for (int q = i; q <= m; q++)
				target[k++] = source[q];
	}

	public void MergePass(ChessMove[] source, ChessMove[] target, int s, int n,
			boolean direction) {
		int i = 0;

		while (i <= n - 2 * s) {
			// 合并大小为s的相邻二段子数组
			if (direction)
				Merge_Asc(source, target, i, i + s - 1, i + 2 * s - 1);
			else
				Merge_Desc(source, target, i, i + s - 1, i + 2 * s - 1);
			i = i + 2 * s;
		}

		if (i + s < n) // 剩余的元素个数小於2s
		{
			if (direction)
				Merge_Asc(source, target, i, i + s - 1, n - 1);
			else
				Merge_Desc(source, target, i, i + s - 1, n - 1);
		} else
			for (int j = i; j <= n - 1; j++)
				target[j] = source[j];
	}

	public void MergeSort(ChessMove[] source, int n, boolean direction) {
		int s = 1;
		while (s < n) {
			MergePass(source, m_TargetBuff, s, n, direction);
			s += s;
			MergePass(m_TargetBuff, source, s, n, direction);
			s += s;
		}
	}

	public void destroy() {
		m_HistoryTable = null;
		m_TargetBuff = null;
	}

}
